package com.red.dubbosimulate.framework;

import com.red.dubbosimulate.framework.protocol.http.HttpClient;
import com.red.dubbosimulate.framework.register.RemoteMapRegister;
import com.red.dubbosimulate.provider.api.HelloService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

public class ProxyFacory {

    public static <T> T getProxy(final Class<T> interfaceClass){

        Object proxyInstance = Proxy.newProxyInstance(ProxyFacory.class.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args){
                try {
                    Invocation invocation = new Invocation(
                            interfaceClass.getName(),method.getName(),method.getParameterTypes(),args
                    );
                    // 获取所有的服务列表
                    List<URL> urls = RemoteMapRegister.get(interfaceClass.getName());
                    URL url = LoadBalance.random(urls);
                    Protocol protocol = ProtocolFactory.getProtocol();
                    String result = protocol.send(url, invocation);
                    return result;
                }catch (Exception e){
                    return "服务访问不通";
                }

            }
        });
        return (T)proxyInstance;
    }
}
